<?php

declare(strict_types=1);

namespace App\Controller\admin;

use App\Constants\ErrorCode;
use App\Controller\AbstractController;
use App\Model\admin\SystemUser;
use App\Request\AdminRequest;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Di\Annotation\Inject;
use Psr\Http\Message\ResponseInterface;

/**
 * 系统用户
 * Class AdminController
 * @package App\Controller\admin
 * @Controller(prefix="admin")
 */
class SystemUserController extends AbstractController
{
    /**
     * @Inject
     * @var SystemUser
     */
    protected $userModel;

    /**
     * 列表
     * @RequestMapping(path="system-user",methods="get")
     * @return ResponseInterface
     */
    public function index(): ResponseInterface
    {
        $page = $this->request->input('page',1);
        $size = $this->request->input('size',10);
        $list = $this->userModel->query()
            ->forPage($page,$size)
            ->orderBy('sort','desc')
            ->orderBy('id','desc')
            ->get();

        $total = $this->userModel->query()->count();

        return $this->success([
            'list' => $list,
            'total' => $total
        ]);
    }

    /**
     * 保存
     * @RequestMapping(path="system-user",methods="post")
     */
    public function store(): ResponseInterface
    {
        $request = $this->container->get(AdminRequest::class);

        $request->scene('create')->validateResolved();

        $save = $this->userModel->saveSystemUser($this->request->all());
        if (isset($save['errMsg']))
            return $this->fail(ErrorCode::BUSINESS_FAIL,$save['errMsg']);

        return $this->success();
    }

    /**
     * 详情
     * @RequestMapping(path="system-user/{id}",methods="get")
     */
    public function show($id): ResponseInterface
    {
        $info = $this->userModel->query()->find($id);
        unset($info->password,$info->salt);
        return $this->success($info);
    }

    /**
     * 更新
     * @RequestMapping(path="system-user",methods="put")
     */
    public function update(): ResponseInterface
    {
        $request = $this->container->get(AdminRequest::class);

        $request->scene('update')->validateResolved();

        $save = $this->userModel->saveSystemUser($request->all());
        if (isset($save['errMsg']))
            return $this->fail(ErrorCode::BUSINESS_FAIL,$save['errMsg']);

        return $this->success();
    }

    /**
     * 删除
     * @RequestMapping(path="system-user/{id}",methods="delete")
     */
    public function destroy($id): ResponseInterface
    {
        if($this->userModel->where('id',$id)->delete()){
            return $this->success();
        }
        return $this->fail(ErrorCode::BUSINESS_FAIL,'删除失败');
    }
}
